from django.shortcuts import render
import os
import shutil
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
import threading
import uuid
from tools.myredis import r
# Create your views here.

def get_folder_size(folder_path):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(folder_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                size = os.path.getsize(fp)
                total_size += size
            except OSError:
                pass  # Ignore files that can't be accessed
    return total_size




class UploadFileView(APIView):
    lock = threading.Lock()


    def post(self, request):
        data = request.data
        file = data['file']
        filename = data['filename']
        tcount = int(data['tcount'])
        print(tcount)
        count = int(data['count'])
        print(count)
        size = int(data['size'])
        arr = filename.split('.')
        fname = uuid.uuid1().hex

        filepath = f'./media/upload/{filename}'

        with self.lock:
            if not os.path.exists(filepath):
                os.mkdir(f'./media/upload/{filename}')
                import time
                r.zset_zadd("fileupload", int(time.time()), filename)

            with open(f'./media/upload/{filename}/{count}', 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)


            fsize = get_folder_size(filepath)

            if size == fsize:
                # 合并
                with open(f'./media/upload/{fname}.{arr[1]}', 'wb') as f:
                    for i in range(tcount):
                        with open(f'./media/upload/{filename}/{i}', 'rb') as chunk:
                            f.write(chunk.read())
                # 删除文件夹
                # if os.path.exists(filepath):
                #     shutil.rmtree(filepath)
                return Response({"code": 200})
            else:
                return Response({"code": 10010})
